#!/bin/bash

#==============================================================================
# 文件统计分析器 (File Analyzer)
#==============================================================================
# 
# 功能描述:
#   深度分析指定目录的文件分布情况，生成详细的统计报告
#   支持文件类型分析、大小分布、时间趋势、存储占用等多维度统计
#
# 作者: Pedro.Pei
# 版本: 1.0
# 更新日期: 2025
#
# 主要功能:
#   📊 文件类型分布统计 - 按扩展名分类统计文件数量和大小
#   📈 文件大小分布分析 - 统计不同大小区间的文件分布
#   📅 时间趋势分析 - 按创建/修改时间分析文件趋势
#   🔍 大文件识别 - 找出占用空间最大的文件
#   📋 详细报告生成 - 支持多种格式输出(文本/CSV/JSON)
#   🗂️ 目录结构分析 - 统计目录层级和文件分布
#
# 使用方法:
#   ./file_analyzer.sh <目录路径> [选项]
#
# 选项:
#   -o, --output <文件>     指定输出报告文件路径
#   -f, --format <格式>     输出格式 (text|csv|json) 默认: text
#   -r, --recursive         递归分析所有子目录
#   -s, --size-limit <大小> 大文件阈值 (如: 100M, 1G) 默认: 100M
#   -t, --top <数量>        显示前N个大文件 默认: 10
#   -d, --depth <层级>      目录分析深度 默认: 3
#   --include-hidden        包含隐藏文件
#   --exclude <模式>        排除文件模式 (如: *.tmp,*.log)
#   -v, --verbose           显示详细处理过程
#   -h, --help             显示帮助信息
#
#==============================================================================

# 脚本配置
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
SCRIPT_NAME=$(basename "$0")

# 默认参数
TARGET_DIR=""
OUTPUT_FILE=""
OUTPUT_FORMAT="text"
RECURSIVE=false
SIZE_LIMIT="100M"
TOP_COUNT=10
MAX_DEPTH=3
INCLUDE_HIDDEN=false
EXCLUDE_PATTERNS=""
VERBOSE=false

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color

# 临时文件用于存储统计数据
TEMP_DIR=$(mktemp -d)
FILE_TYPES_FILE="$TEMP_DIR/file_types.txt"
FILE_SIZES_FILE="$TEMP_DIR/file_sizes.txt"
MONTHLY_STATS_FILE="$TEMP_DIR/monthly_stats.txt"
DIRECTORY_STATS_FILE="$TEMP_DIR/directory_stats.txt"
LARGE_FILES_FILE="$TEMP_DIR/large_files.txt"

# 统计变量
total_files=0
total_size=0
total_dirs=0
start_time=$(date +%s)

# 清理临时文件
cleanup_temp() {
    rm -rf "$TEMP_DIR" 2>/dev/null
}
trap cleanup_temp EXIT

# 显示帮助信息
show_help() {
    echo -e "${CYAN}文件统计分析器 v1.0${NC}"
    echo ""
    echo "用法: $0 <目录路径> [选项]"
    echo ""
    echo -e "${WHITE}选项:${NC}"
    echo -e "  ${GREEN}-o, --output <文件>${NC}     指定输出报告文件路径"
    echo -e "  ${GREEN}-f, --format <格式>${NC}     输出格式 (text|csv|json) 默认: text"
    echo -e "  ${GREEN}-r, --recursive${NC}         递归分析所有子目录"
    echo -e "  ${GREEN}-s, --size-limit <大小>${NC} 大文件阈值 (如: 100M, 1G) 默认: 100M"
    echo -e "  ${GREEN}-t, --top <数量>${NC}        显示前N个大文件 默认: 10"
    echo -e "  ${GREEN}-d, --depth <层级>${NC}      目录分析深度 默认: 3"
    echo -e "  ${GREEN}--include-hidden${NC}        包含隐藏文件"
    echo -e "  ${GREEN}--exclude <模式>${NC}        排除文件模式 (如: *.tmp,*.log)"
    echo -e "  ${GREEN}-v, --verbose${NC}           显示详细处理过程"
    echo -e "  ${GREEN}-h, --help${NC}             显示此帮助信息"
    echo ""
    echo -e "${WHITE}示例:${NC}"
    echo "  $0 ~/Downloads"
    echo "  $0 ~/Documents -r -f csv -o report.csv"
    echo "  $0 ~/Videos -s 500M -t 20"
    echo "  $0 ~/Projects -r --include-hidden -v"
    echo ""
    echo -e "${WHITE}输出格式:${NC}"
    echo -e "  ${GREEN}text${NC}  - 人类可读的文本报告"
    echo -e "  ${GREEN}csv${NC}   - CSV格式，便于Excel分析"
    echo -e "  ${GREEN}json${NC}  - JSON格式，便于程序处理"
}

# 解析命令行参数
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -o|--output)
                OUTPUT_FILE="$2"
                shift 2
                ;;
            -f|--format)
                OUTPUT_FORMAT="$2"
                if [[ ! "$OUTPUT_FORMAT" =~ ^(text|csv|json)$ ]]; then
                    echo -e "${RED}错误: 不支持的输出格式 '$OUTPUT_FORMAT'${NC}"
                    exit 1
                fi
                shift 2
                ;;
            -r|--recursive)
                RECURSIVE=true
                shift
                ;;
            -s|--size-limit)
                SIZE_LIMIT="$2"
                shift 2
                ;;
            -t|--top)
                TOP_COUNT="$2"
                if ! [[ "$TOP_COUNT" =~ ^[0-9]+$ ]]; then
                    echo -e "${RED}错误: top参数必须是数字${NC}"
                    exit 1
                fi
                shift 2
                ;;
            -d|--depth)
                MAX_DEPTH="$2"
                if ! [[ "$MAX_DEPTH" =~ ^[0-9]+$ ]]; then
                    echo -e "${RED}错误: depth参数必须是数字${NC}"
                    exit 1
                fi
                shift 2
                ;;
            --include-hidden)
                INCLUDE_HIDDEN=true
                shift
                ;;
            --exclude)
                EXCLUDE_PATTERNS="$2"
                shift 2
                ;;
            -v|--verbose)
                VERBOSE=true
                shift
                ;;
            -*)
                echo -e "${RED}错误: 未知选项 '$1'${NC}"
                show_help
                exit 1
                ;;
            *)
                if [ -z "$TARGET_DIR" ]; then
                    TARGET_DIR="$1"
                else
                    echo -e "${RED}错误: 只能指定一个目录${NC}"
                    exit 1
                fi
                shift
                ;;
        esac
    done

    # 检查必需参数
    if [ -z "$TARGET_DIR" ]; then
        echo -e "${RED}错误: 请指定要分析的目录${NC}"
        show_help
        exit 1
    fi

    # 验证目录存在
    if [ ! -d "$TARGET_DIR" ]; then
        echo -e "${RED}错误: 目录不存在 '$TARGET_DIR'${NC}"
        exit 1
    fi

    # 转换为绝对路径
    TARGET_DIR=$(cd "$TARGET_DIR" && pwd)
}

# 转换大小单位为字节
convert_size_to_bytes() {
    local size="$1"
    local number=$(echo "$size" | sed 's/[^0-9.]//g')
    local unit=$(echo "$size" | sed 's/[0-9.]//g' | tr '[:lower:]' '[:upper:]')
    
    case "$unit" in
        "K"|"KB")
            echo "$(echo "$number * 1024" | bc -l | cut -d. -f1)"
            ;;
        "M"|"MB")
            echo "$(echo "$number * 1024 * 1024" | bc -l | cut -d. -f1)"
            ;;
        "G"|"GB")
            echo "$(echo "$number * 1024 * 1024 * 1024" | bc -l | cut -d. -f1)"
            ;;
        "T"|"TB")
            echo "$(echo "$number * 1024 * 1024 * 1024 * 1024" | bc -l | cut -d. -f1)"
            ;;
        *)
            echo "$number"
            ;;
    esac
}

# 格式化文件大小
format_size() {
    local bytes=$1
    if [ "$bytes" -eq 0 ]; then
        echo "0 B"
    elif [ "$bytes" -lt 1024 ]; then
        echo "${bytes} B"
    elif [ "$bytes" -lt 1048576 ]; then
        echo "$(echo "scale=1; $bytes/1024" | bc) KB"
    elif [ "$bytes" -lt 1073741824 ]; then
        echo "$(echo "scale=1; $bytes/1048576" | bc) MB"
    elif [ "$bytes" -lt 1099511627776 ]; then
        echo "$(echo "scale=1; $bytes/1073741824" | bc) GB"
    else
        echo "$(echo "scale=1; $bytes/1099511627776" | bc) TB"
    fi
}

# 获取文件扩展名
get_extension() {
    local filename="$1"
    local ext="${filename##*.}"
    if [ "$ext" = "$filename" ]; then
        echo "(无扩展名)"
    else
        echo "$ext" | tr '[:upper:]' '[:lower:]'
    fi
}

# 获取文件大小区间
get_size_category() {
    local size=$1
    if [ "$size" -eq 0 ]; then
        echo "空文件"
    elif [ "$size" -lt 1024 ]; then
        echo "< 1KB"
    elif [ "$size" -lt 10240 ]; then
        echo "1KB - 10KB"
    elif [ "$size" -lt 102400 ]; then
        echo "10KB - 100KB"
    elif [ "$size" -lt 1048576 ]; then
        echo "100KB - 1MB"
    elif [ "$size" -lt 10485760 ]; then
        echo "1MB - 10MB"
    elif [ "$size" -lt 104857600 ]; then
        echo "10MB - 100MB"
    elif [ "$size" -lt 1073741824 ]; then
        echo "100MB - 1GB"
    else
        echo "> 1GB"
    fi
}

# 更新文件类型统计
update_file_type_stats() {
    local ext="$1"
    local size="$2"
    
    # 检查是否已存在
    if grep -q "^$ext|" "$FILE_TYPES_FILE" 2>/dev/null; then
        # 更新现有记录
        local current_line=$(grep "^$ext|" "$FILE_TYPES_FILE")
        local current_count=$(echo "$current_line" | cut -d'|' -f2)
        local current_size=$(echo "$current_line" | cut -d'|' -f3)
        local new_count=$((current_count + 1))
        local new_size=$((current_size + size))
        
        # 替换行
        sed -i "" "s/^$ext|.*/$ext|$new_count|$new_size/" "$FILE_TYPES_FILE"
    else
        # 添加新记录
        echo "$ext|1|$size" >> "$FILE_TYPES_FILE"
    fi
}

# 更新大小分布统计
update_size_stats() {
    local category="$1"
    
    if grep -q "^$category|" "$FILE_SIZES_FILE" 2>/dev/null; then
        local current_count=$(grep "^$category|" "$FILE_SIZES_FILE" | cut -d'|' -f2)
        local new_count=$((current_count + 1))
        sed -i "" "s/^$category|.*/$category|$new_count/" "$FILE_SIZES_FILE"
    else
        echo "$category|1" >> "$FILE_SIZES_FILE"
    fi
}

# 更新月度统计
update_monthly_stats() {
    local month="$1"
    
    if grep -q "^$month|" "$MONTHLY_STATS_FILE" 2>/dev/null; then
        local current_count=$(grep "^$month|" "$MONTHLY_STATS_FILE" | cut -d'|' -f2)
        local new_count=$((current_count + 1))
        sed -i "" "s/^$month|.*/$month|$new_count/" "$MONTHLY_STATS_FILE"
    else
        echo "$month|1" >> "$MONTHLY_STATS_FILE"
    fi
}

# 分析单个文件
analyze_file() {
    local filepath="$1"
    local filename=$(basename "$filepath")
    local filesize=$(stat -f%z "$filepath" 2>/dev/null || echo 0)
    local modify_time=$(stat -f%m "$filepath" 2>/dev/null || echo 0)
    local month=$(date -r "$modify_time" "+%Y-%m" 2>/dev/null || echo "未知")
    
    # 跳过隐藏文件(如果设置)
    if [ "$INCLUDE_HIDDEN" = false ] && [[ "$filename" == .* ]]; then
        return
    fi
    
    # 检查排除模式
    if [ -n "$EXCLUDE_PATTERNS" ]; then
        IFS=',' read -ra PATTERNS <<< "$EXCLUDE_PATTERNS"
        for pattern in "${PATTERNS[@]}"; do
            if [[ "$filename" == $pattern ]]; then
                return
            fi
        done
    fi
    
    # 更新统计
    local ext=$(get_extension "$filename")
    local size_cat=$(get_size_category "$filesize")
    
    # 更新各种统计
    update_file_type_stats "$ext" "$filesize"
    update_size_stats "$size_cat"
    update_monthly_stats "$month"
    
    # 大文件记录
    local size_limit_bytes=$(convert_size_to_bytes "$SIZE_LIMIT")
    if [ "$filesize" -gt "$size_limit_bytes" ]; then
        echo "$filesize|$filepath" >> "$LARGE_FILES_FILE"
    fi
    
    # 全局统计
    total_files=$((total_files + 1))
    total_size=$((total_size + filesize))
    
    if [ "$VERBOSE" = true ]; then
        echo -e "${BLUE}分析文件:${NC} $filepath ($(format_size $filesize))"
    fi
}

# 分析目录
analyze_directory() {
    local dirpath="$1"
    local current_depth="$2"
    
    if [ "$current_depth" -gt "$MAX_DEPTH" ] && [ "$RECURSIVE" = true ]; then
        return
    fi
    
    local dir_files=0
    local dir_size=0
    
    if [ "$VERBOSE" = true ]; then
        echo -e "${CYAN}分析目录:${NC} $dirpath"
    elif [ "$current_depth" -le 2 ]; then
        # 对于浅层目录，即使非verbose模式也显示进度
        local relative_path=$(echo "$dirpath" | sed "s|$TARGET_DIR|.|")
        echo -e "${GRAY}正在分析: $relative_path${NC}" >&2
    fi
    
    # 分析当前目录的文件
    while IFS= read -r -d '' file; do
        if [ -f "$file" ]; then
            analyze_file "$file"
            local filesize=$(stat -f%z "$file" 2>/dev/null || echo 0)
            dir_files=$((dir_files + 1))
            dir_size=$((dir_size + filesize))
        fi
    done < <(find "$dirpath" -maxdepth 1 -type f -print0 2>/dev/null)
    
    # 记录目录统计
    echo "$dirpath|$dir_files|$dir_size" >> "$DIRECTORY_STATS_FILE"
    total_dirs=$((total_dirs + 1))
    
    # 递归处理子目录
    if [ "$RECURSIVE" = true ]; then
        while IFS= read -r -d '' subdir; do
            if [ -d "$subdir" ] && [ "$subdir" != "$dirpath" ]; then
                analyze_directory "$subdir" $((current_depth + 1))
            fi
        done < <(find "$dirpath" -maxdepth 1 -type d -print0 2>/dev/null)
    fi
}

# 生成文本格式报告
generate_text_report() {
    local output="$1"
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    {
        echo "==========================================="
        echo "         文件统计分析报告"
        echo "==========================================="
        echo ""
        echo "分析目录: $TARGET_DIR"
        echo "分析时间: $(date)"
        echo "处理耗时: ${duration}秒"
        echo "递归模式: $([ "$RECURSIVE" = true ] && echo "是" || echo "否")"
        echo ""
        
        echo "📊 总体统计"
        echo "-------------------------------------------"
        echo "总文件数: $total_files"
        echo "总目录数: $total_dirs"
        echo "总大小: $(format_size $total_size)"
        if [ "$total_files" -gt 0 ]; then
            echo "平均大小: $(format_size $((total_size / total_files)))"
        fi
        echo ""
        
        echo "📁 文件类型分布 (前20种)"
        echo "-------------------------------------------"
        printf "%-15s %10s %15s %10s\n" "扩展名" "文件数" "总大小" "占比"
        echo "-------------------------------------------"
        
        # 按文件数量排序显示文件类型
        if [ -f "$FILE_TYPES_FILE" ]; then
            sort -t'|' -k2 -nr "$FILE_TYPES_FILE" | head -20 | while IFS='|' read -r ext count size; do
                local percentage=$(echo "scale=1; $size * 100 / $total_size" | bc -l 2>/dev/null || echo "0")
                printf "%-15s %10d %15s %9s%%\n" "$ext" "$count" "$(format_size $size)" "$percentage"
            done
        fi
        echo ""
        
        echo "📈 文件大小分布"
        echo "-------------------------------------------"
        printf "%-20s %10s\n" "大小区间" "文件数"
        echo "-------------------------------------------"
        if [ -f "$FILE_SIZES_FILE" ]; then
            for category in "空文件" "< 1KB" "1KB - 10KB" "10KB - 100KB" "100KB - 1MB" "1MB - 10MB" "10MB - 100MB" "100MB - 1GB" "> 1GB"; do
                local count=$(grep "^$category|" "$FILE_SIZES_FILE" 2>/dev/null | cut -d'|' -f2)
                if [ -z "$count" ]; then
                    count=0
                fi
                if [ "$count" -gt 0 ]; then
                    printf "%-20s %10d\n" "$category" "$count"
                fi
            done
        fi
        echo ""
        
        echo "📅 文件时间分布 (按修改时间)"
        echo "-------------------------------------------"
        printf "%-10s %10s\n" "月份" "文件数"
        echo "-------------------------------------------"
        if [ -f "$MONTHLY_STATS_FILE" ]; then
            sort -t'|' -k1 -r "$MONTHLY_STATS_FILE" | head -12 | while IFS='|' read -r month count; do
                printf "%-10s %10d\n" "$month" "$count"
            done
        fi
        echo ""
        
        echo "🔍 大文件列表 (>${SIZE_LIMIT})"
        echo "-------------------------------------------"
        if [ -f "$LARGE_FILES_FILE" ] && [ -s "$LARGE_FILES_FILE" ]; then
            printf "%-15s %s\n" "文件大小" "文件路径"
            echo "-------------------------------------------"
            
            # 排序大文件列表并显示前N个
            sort -t'|' -k1 -nr "$LARGE_FILES_FILE" | head -"$TOP_COUNT" | while IFS='|' read -r size path; do
                printf "%-15s %s\n" "$(format_size $size)" "$path"
            done
        else
            echo "未发现大于 ${SIZE_LIMIT} 的文件"
        fi
        echo ""
        
        if [ "$RECURSIVE" = true ] && [ -f "$DIRECTORY_STATS_FILE" ]; then
            echo "📂 目录统计 (前10个最大目录)"
            echo "-------------------------------------------"
            printf "%-50s %10s %15s\n" "目录路径" "文件数" "总大小"
            echo "-------------------------------------------"
            
            # 按大小排序目录
            sort -t'|' -k3 -nr "$DIRECTORY_STATS_FILE" | head -10 | while IFS='|' read -r dir files size; do
                local short_path=$(echo "$dir" | sed "s|$TARGET_DIR|.|")
                printf "%-50s %10d %15s\n" "$short_path" "$files" "$(format_size $size)"
            done
        fi
        
        echo ""
        echo "==========================================="
        echo "报告生成完成 - $(date)"
        echo "==========================================="
        
    } > "$output"
}

# 生成CSV格式报告
generate_csv_report() {
    local output="$1"
    
    {
        echo "类型,扩展名,文件数,总大小(字节),总大小(格式化),占比(%)"
        
        if [ -f "$FILE_TYPES_FILE" ]; then
            while IFS='|' read -r ext count size; do
                local percentage=$(echo "scale=2; $size * 100 / $total_size" | bc -l 2>/dev/null || echo "0")
                echo "文件类型,$ext,$count,$size,$(format_size $size),$percentage"
            done < "$FILE_TYPES_FILE"
        fi
        
        echo ""
        echo "类型,大小区间,文件数"
        if [ -f "$FILE_SIZES_FILE" ]; then
            while IFS='|' read -r category count; do
                echo "大小分布,$category,$count"
            done < "$FILE_SIZES_FILE"
        fi
        
        echo ""
        echo "类型,月份,文件数"
        if [ -f "$MONTHLY_STATS_FILE" ]; then
            while IFS='|' read -r month count; do
                echo "时间分布,$month,$count"
            done < "$MONTHLY_STATS_FILE"
        fi
        
    } > "$output"
}

# 生成JSON格式报告
generate_json_report() {
    local output="$1"
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    
    {
        echo "{"
        echo "  \"analysis_info\": {"
        echo "    \"target_directory\": \"$TARGET_DIR\","
        echo "    \"analysis_time\": \"$(date -Iseconds)\","
        echo "    \"duration_seconds\": $duration,"
        echo "    \"recursive_mode\": $([ "$RECURSIVE" = true ] && echo "true" || echo "false")"
        echo "  },"
        echo "  \"summary\": {"
        echo "    \"total_files\": $total_files,"
        echo "    \"total_directories\": $total_dirs,"
        echo "    \"total_size_bytes\": $total_size,"
        echo "    \"total_size_formatted\": \"$(format_size $total_size)\""
        if [ "$total_files" -gt 0 ]; then
            echo "    ,\"average_size_bytes\": $((total_size / total_files))"
        fi
        echo "  },"
        echo "  \"file_types\": {"
        
        local first=true
        if [ -f "$FILE_TYPES_FILE" ]; then
            while IFS='|' read -r ext count size; do
                if [ "$first" = false ]; then
                    echo ","
                fi
                local percentage=$(echo "scale=2; $size * 100 / $total_size" | bc -l 2>/dev/null || echo "0")
                echo -n "    \"$ext\": {\"count\": $count, \"size_bytes\": $size, \"size_formatted\": \"$(format_size $size)\", \"percentage\": $percentage}"
                first=false
            done < "$FILE_TYPES_FILE"
        fi
        echo ""
        echo "  },"
        echo "  \"size_distribution\": {"
        
        first=true
        if [ -f "$FILE_SIZES_FILE" ]; then
            while IFS='|' read -r category count; do
                if [ "$first" = false ]; then
                    echo ","
                fi
                echo -n "    \"$category\": $count"
                first=false
            done < "$FILE_SIZES_FILE"
        fi
        echo ""
        echo "  },"
        echo "  \"monthly_distribution\": {"
        
        first=true
        if [ -f "$MONTHLY_STATS_FILE" ]; then
            while IFS='|' read -r month count; do
                if [ "$first" = false ]; then
                    echo ","
                fi
                echo -n "    \"$month\": $count"
                first=false
            done < "$MONTHLY_STATS_FILE"
        fi
        echo ""
        echo "  }"
        echo "}"
        
    } > "$output"
}

# 主函数
main() {
    local start_time=$(date +%s)
    echo -e "${CYAN}🔍 文件统计分析器 v1.0${NC}"
    echo -e "${YELLOW}开始分析目录: $TARGET_DIR${NC}"
    if [ "$VERBOSE" = true ]; then
        echo -e "${YELLOW}开始时间: $(date)${NC}"
    fi
    echo ""
    
    # 开始分析
    echo -e "${GRAY}正在扫描文件...${NC}"
    analyze_directory "$TARGET_DIR" 1
    
    local end_time=$(date +%s)
    local duration=$((end_time - start_time))
    echo -e "${GREEN}✅ 分析完成!${NC}"
    echo -e "${BLUE}处理了 $total_files 个文件，$total_dirs 个目录${NC}"
    echo -e "${BLUE}总大小: $(format_size $total_size)${NC}"
    echo -e "${BLUE}分析耗时: ${duration}秒${NC}"
    echo ""
    
    # 生成报告
    local report_file
    if [ -n "$OUTPUT_FILE" ]; then
        report_file="$OUTPUT_FILE"
    else
        local timestamp=$(date +"%Y%m%d_%H%M%S")
        case "$OUTPUT_FORMAT" in
            "csv")
                report_file="file_analysis_${timestamp}.csv"
                ;;
            "json")
                report_file="file_analysis_${timestamp}.json"
                ;;
            *)
                report_file="file_analysis_${timestamp}.txt"
                ;;
        esac
    fi
    
    echo -e "${YELLOW}生成 $OUTPUT_FORMAT 格式报告...${NC}"
    
    case "$OUTPUT_FORMAT" in
        "csv")
            generate_csv_report "$report_file"
            ;;
        "json")
            generate_json_report "$report_file"
            ;;
        *)
            generate_text_report "$report_file"
            ;;
    esac
    
    echo -e "${GREEN}📊 报告已生成: $report_file${NC}"
    
    # 如果是文本格式且没有指定输出文件，显示报告内容
    if [ "$OUTPUT_FORMAT" = "text" ] && [ -z "$OUTPUT_FILE" ]; then
        echo ""
        echo -e "${CYAN}==================== 报告内容 ====================${NC}"
        cat "$report_file"
    fi
}

# 检查依赖
check_dependencies() {
    local missing_deps=()
    
    if ! command -v bc &> /dev/null; then
        missing_deps+=("bc")
    fi
    
    if ! command -v stat &> /dev/null; then
        missing_deps+=("stat")
    fi
    
    if [ ${#missing_deps[@]} -gt 0 ]; then
        echo -e "${RED}错误: 缺少必需的依赖:${NC}"
        for dep in "${missing_deps[@]}"; do
            echo -e "  ${YELLOW}- $dep${NC}"
        done
        echo ""
        echo -e "${BLUE}安装方法:${NC}"
        echo "  macOS: brew install bc"
        echo "  Ubuntu/Debian: sudo apt install bc"
        echo "  CentOS/RHEL: sudo yum install bc"
        exit 1
    fi
}

# 脚本入口
if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
    # 检查依赖
    check_dependencies
    
    # 解析参数
    parse_arguments "$@"
    
    # 执行主函数
    main
fi